/*
 * @(#)BinaryDownloadResult.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.result.direct;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.nhncorp.lucy.web.helper.ServletHelper;

import com.nhncorp.usf.core.config.runtime.ResultPageInfo;

/**
 * @author Web Platform Development Team
 */
public class BinaryDownloadResult extends AbstractDirectResult {
    private static final long serialVersionUID = -4274636474484605851L;

    /**
     *
     * @param resultPageInfo the page information
     * @param dataMap the usf result data
     * @throws Exception the Exception
     */
    @Override
    public void execute(ResultPageInfo resultPageInfo, Map<String, Object> dataMap) throws Exception {
        HttpServletResponse response = ServletHelper.getResponse();

        String serverFileName = (String)dataMap.get("serverFileName");
        String downloadFileName = (String)dataMap.get("downloadFileName");
        File file = new File(serverFileName);
        int length = 0;
        ServletOutputStream op = response.getOutputStream();
        ServletContext context = ServletHelper.getServletContext();
        String mimetype = null;

        if (context != null) {
            mimetype = context.getMimeType(serverFileName);
        }

        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int)file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");

        byte[] bbuf = new byte[1024];
        FileInputStream fis = new FileInputStream(file);
        DataInputStream in = new DataInputStream(fis);

        try {
	        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
	            op.write(bbuf, 0, length);
	        }
        } finally {
        	if (fis != null) {
        		fis.close();
        	}
        	if (in != null) {
        		in.close();
        	}
        }
        
        op.flush();
        op.close();
    }
}